package org.kingkong.framework.grid;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.kingkong.framework.annotation.Grid;
import org.kingkong.framework.annotation.GridColumn;

public class GridAnnotationResolver {

	private ClassLoader classLoader = GridAnnotationResolver.class
			.getClassLoader();

	private final static Logger logger = Logger
			.getLogger("GridAnnotationResolver");

	protected String definition;

	private List<GridColumn> columns;

	private Grid grid;

	private Class<?> clazz;

	public GridAnnotationResolver(final String definition) {
		try {
			this.clazz = classLoader.loadClass(definition);
			this.definition = definition;
			resolveGrid();
			resolveColumns();
		} catch (final Exception e) {
			logger.severe(e.getMessage());
		}
	}

	private void resolveColumns() throws Exception {

		columns = new ArrayList<GridColumn>();

		final Field[] fields = clazz.getDeclaredFields();

		for (int i = 0; i < fields.length; i++) {
			final GridColumn gridColumnAnnotaion = fields[i]
					.getAnnotation(GridColumn.class);
			if (gridColumnAnnotaion != null) {
				columns.add(gridColumnAnnotaion);
			}
		}
	}

	private void resolveGrid() {
		this.grid = clazz.getAnnotation(Grid.class);
	}

	public List<GridColumn> getColumns() {
		return columns;
	}

	public void setColumns(List<GridColumn> columns) {
		this.columns = columns;
	}

	public Grid getGrid() {
		return grid;
	}

	public void setGrid(Grid grid) {
		this.grid = grid;
	}
}
